# -*- coding: utf-8 -*-
__author__ = 'liubei'

from mongoengine import *
import db_engine
import csv
import time
import surveyInstanceDB
import aes
import datetime

def exportBMQ():
    connect('az', host=db_engine.host)
    results = db_engine.SurveyResult.objects(name='BMQ-G')
    offlineResults = db_engine.SurveyResultOffline.objects(name='BMQ-G')
    survey = db_engine.Survey.objects(name='BMQ-G')[0]

    aes_cipher = aes.AESCipher(aes.aes_key)
    with open('static/bmq_g.csv', 'wb') as csvfile:
        fieldnames = ['STUDY', 'SUBJECT', 'PART', 'VISIT', 'LINE', 'VIS_DAT', 'QSCAT', 'PROTSCHD',
                      'BMQDAT', 'BMQTIM', 'BMQ1', 'BMQ2', 'BMQ3', 'BMQ4', 'BMQ5', 'BMQ6', 'BMQ7', 'BMQ8', 'BMQ9', 'APP']
        spamwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
        spamwriter.writeheader()
        filterMap = {}
        # app data
        for result in results:
            print result.surveyResults
            print result.userPhone
            user = db_engine.queryUser(result.userPhone)
            if user != None:
                nDate = time.strftime('%Y/%m/%d', time.localtime(result.createdDate))
                #
                nTmpDate = time.strftime('%Y/%m', time.localtime(result.createdDate))
                filterMap[user.patientCode + "_" + nTmpDate] = 1

                nTime = time.strftime('%H:%M', time.localtime(result.createdDate))
                choiceList = []
                for page in survey.surveies:
                    for surveyResult in result.surveyResults:
                        if str(page.id) == surveyResult['uid']:
                            choiceIndex = 1
                            if str(page.type) == '0':
                                for choice in page.choices:
                                    # print type(aes_cipher.decryptWithUnicode(surveyResult['choice']))
                                    # print type(choice.encode('utf-8'))
                                    try:
                                        if aes_cipher.decryptWithUnicode(surveyResult['choice']) == choice.encode(
                                                'utf-8'):
                                            choiceList.append(choiceIndex)
                                            break
                                    except Exception as error:
                                        print error
                                    choiceIndex += 1
                bmqDic = {'STUDY': 'D3560C00088', 'SUBJECT': user.patientCode, 'LINE': '1', 'QSCAT': 'BMQ-G',
                          'BMQDAT': nDate, 'BMQTIM': nTime, 'APP': 1}
                print choiceList
                for i in range(0, len(choiceList), 1):
                    if i <= 8:
                        key = 'BMQ' + str(i + 1)
                        bmqDic[key] = choiceList[i]
                surveySchedule = surveyInstanceDB.SurveySchedule.objects(userPhone=user.userPhone)[0]
                interface = surveyInstanceDB.calDayInterval(surveySchedule.firstDone, result.createdDate)
                if interface < 24:
                    bmqDic['VISIT'] = 1
                    bmqDic['LINE'] = 1
                    bmqDic['PROTSCHD'] = 'w0'
                    fDate = time.strftime('%Y/%m/%d', time.localtime(surveySchedule.firstDone))
                    if surveySchedule.firstDone == 0:
                        fDate = time.strftime('%Y/%m/%d', time.localtime(surveySchedule.lastDone))
                    bmqDic['VIS_DAT'] = fDate
                else:
                    bmqDic['VISIT'] = 2
                    bmqDic['LINE'] = 2
                    bmqDic['PROTSCHD'] = 'w24'
                    fDate = time.strftime('%Y/%m/%d', time.localtime(surveySchedule.firstDone + 24 * 7 * 24 * 60 * 60))
                    bmqDic['VIS_DAT'] = fDate
                spamwriter.writerow(bmqDic)
        # offline data
        print offlineResults.count()
        for result in offlineResults:
            print result.surveyResults
            nDate = time.strftime('%Y/%m/%d', time.localtime(result.createdDate))

            nTmpDate = time.strftime('%Y/%m', time.localtime(result.createdDate))
            app = 0
            if filterMap.has_key(result.patientCode + "_" + nTmpDate):
                print '=============================== ' + result.patientCode + "_" + nTmpDate + ' ==============================='
                app = -1

            nTime = time.strftime('%H:%M', time.localtime(result.createdDate))

            bmqDic = {'STUDY': 'D3560C00088', 'SUBJECT': result.patientCode, 'LINE': '1', 'QSCAT': 'BMQ-G',
                      'BMQDAT': nDate, 'BMQTIM': nTime, 'APP': app}
            for i in range(0, len(result.surveyResults), 1):
                key = 'BMQ' + str(i + 1)
                bmqDic[key] = result.surveyResults[i]

            spamwriter.writerow(bmqDic)


def exportLSQ(lsq):
    connect('az', host=db_engine.host)
    results = db_engine.SurveyResult.objects(name=lsq)
    offlineResults = db_engine.SurveyResultOffline.objects(name=lsq)
    survey = db_engine.Survey.objects(name=lsq)[0]

    aes_cipher = aes.AESCipher(aes.aes_key)
    with open('static/' + lsq + '.csv', 'wb') as csvfile:
        fieldnames = ['STUDY', 'SUBJECT', 'PART', 'VISIT', 'LINE', 'VIS_DAT', 'QSCAT', 'PROTSCHD',
                      'LSQDAT', 'LSQTIM', 'LSQ1', 'LSQ2', 'LSQ3', 'LSQ4', 'LSQ5', 'APP']
        spamwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
        spamwriter.writeheader()

        filterMap = {}

        for result in results:
            print result.surveyResults
            print result.userPhone
            user = db_engine.queryUser(result.userPhone)
            if user != None:
                filterMap[user.patientCode] = 1

                nDate = time.strftime('%Y/%m/%d', time.localtime(result.createdDate))
                nTime = time.strftime('%H:%M', time.localtime(result.createdDate))
                choiceList = []
                for page in survey.surveies:
                    for surveyResult in result.surveyResults:
                        if str(page.id) == surveyResult['uid']:
                            choiceIndex = 1
                            if str(page.type) == '0':
                                for choice in page.choices:
                                    if aes_cipher.decryptWithUnicode(surveyResult['choice']) == choice.encode('utf-8'):
                                        choiceList.append(choiceIndex)
                                        break
                                    choiceIndex += 1
                bmqDic = {'STUDY': 'D3560C00088', 'SUBJECT': user.patientCode, 'LINE': '1', 'QSCAT': lsq,
                          'LSQDAT': nDate, 'LSQTIM': nTime, "APP": 1}
                print choiceList
                for i in range(0, len(choiceList), 1):
                    key = 'LSQ' + str(i + 1)
                    bmqDic[key] = choiceList[i]
                surveySchedule = surveyInstanceDB.SurveySchedule.objects(userPhone=user.userPhone)[0]
                interface = surveyInstanceDB.calDayInterval(surveySchedule.firstDone, result.createdDate)
                if interface == 0:
                    bmqDic['VISIT'] = 1
                    bmqDic['PROTSCHD'] = 'w0'
                    fDate = time.strftime('%Y/%m/%d', time.localtime(surveySchedule.firstDone))
                    bmqDic['VIS_DAT'] = fDate
                else:
                    bmqDic['VISIT'] = 2
                    bmqDic['PROTSCHD'] = 'w24'
                    fDate = time.strftime('%Y/%m/%d', time.localtime(surveySchedule.firstDone + 24 * 7 * 24 * 60 * 60))
                    bmqDic['VIS_DAT'] = fDate
                spamwriter.writerow(bmqDic)
        # offline data
        for result in offlineResults:
            print result.surveyResults
            app = 0
            if filterMap.has_key(result.patientCode):
                print '=============================== ' + result.patientCode + ' ==============================='
                app = -1

            nDate = time.strftime('%Y/%m/%d', time.localtime(result.createdDate))
            nTime = time.strftime('%H:%M', time.localtime(result.createdDate))

            bmqDic = {'STUDY': 'D3560C00088', 'SUBJECT': result.patientCode, 'LINE': '1', 'QSCAT': lsq,
                      'LSQDAT': nDate, 'LSQTIM': nTime, "APP": app}
            for i in range(0, len(result.surveyResults), 1):
                key = 'LSQ' + str(i + 1)
                bmqDic[key] = result.surveyResults[i]

            spamwriter.writerow(bmqDic)


def exportRAQ():
    connect('az', host=db_engine.host)
    results = db_engine.SurveyResult.objects(name='RAQ')
    offlineResults = db_engine.SurveyResultOffline.objects(name='RAQ')
    print results.count()
    survey = db_engine.Survey.objects(name='RAQ')[0]
    aes_cipher = aes.AESCipher(aes.aes_key)

    with open('static/raq.csv', 'wb') as csvfile:
        fieldnames = ['STUDY', 'SUBJECT', 'PART', 'VISIT', 'LINE', 'VIS_DAT', 'QSCAT', 'PROTSCHD',
                      'RAQDAT', 'RAQTIM', 'RAQ1', 'RAQ2', 'RAQ3', 'RAQ4', 'RAQ5', 'RAQ6', 'RAQ7', 'RAQ8',
                      'RAQ9', 'RAQ10', 'RAQ11', 'RAQ12', "APP"]
        spamwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
        spamwriter.writeheader()
        filterMap = {}

        for result in results:
            print result.surveyResults
            print result.userPhone
            user = db_engine.queryUser(result.userPhone)
            if user != None:
                nDate = time.strftime('%Y/%m/%d', time.localtime(result.createdDate))
                #
                nTmpDate = time.strftime('%Y/%m', time.localtime(result.createdDate))
                filterMap[user.patientCode + "_" + nTmpDate] = 1

                nTime = time.strftime('%H:%M', time.localtime(result.createdDate))
                choiceList = []
                for page in survey.surveies:
                    findSurvey = False
                    for surveyResult in result.surveyResults:
                        if str(page.id) == surveyResult['uid']:
                            findSurvey = True
                            choiceIndex = 1
                            if str(page.type) == '0':
                                for choice in page.choices:
                                    if aes_cipher.decryptWithUnicode(surveyResult['choice']) == choice.encode('utf-8'):
                                        choiceList.append(choiceIndex)
                                        break
                                    choiceIndex += 1
                            else:
                                choiceList.append(aes_cipher.decrypt(surveyResult['choice']))
                    if not findSurvey:
                        choiceList.append("")

                bmqDic = {'STUDY': 'D3560C00088', 'SUBJECT': user.patientCode, 'LINE': '1', 'QSCAT': 'RAQ',
                          'RAQDAT': nDate, 'RAQTIM': nTime, "APP": 1}
                print choiceList
                for i in range(0, len(choiceList), 1):
                    key = 'RAQ' + str(i + 1)
                    bmqDic[key] = str(choiceList[i]).replace("\\", '')
                surveySchedule = surveyInstanceDB.SurveySchedule.objects(userPhone=user.userPhone)[0]
                interface = surveyInstanceDB.calDayInterval(surveySchedule.firstDone, result.createdDate)
                fDate = time.strftime('%Y/%m/%d',
                                      time.localtime(surveySchedule.firstDone + interface * 7 * 24 * 60 * 60))
                bmqDic['VIS_DAT'] = fDate
                if interface < 24:
                    bmqDic['VISIT'] = 1
                else:
                    bmqDic['VISIT'] = 2
                bmqDic['PROTSCHD'] = 'w' + str(interface)
                spamwriter.writerow(bmqDic)

        # offline data
        print offlineResults.count()
        for result in offlineResults:
            print result.surveyResults
            nDate = time.strftime('%Y/%m/%d', time.localtime(result.createdDate))
            nTime = time.strftime('%H:%M', time.localtime(result.createdDate))

            nTmpDate = time.strftime('%Y/%m', time.localtime(result.createdDate))
            app = 0
            if filterMap.has_key(result.patientCode + "_" + nTmpDate):
                print '=============================== ' + result.patientCode + "_" + nTmpDate + ' ==============================='
                app = -1

            bmqDic = {'STUDY': 'D3560C00088', 'SUBJECT': result.patientCode, 'LINE': '1', 'QSCAT': 'RAQ',
                      'RAQDAT': nDate, 'RAQTIM': nTime, "APP": app}
            for i in range(0, len(result.surveyResults), 1):
                key = 'RAQ' + str(i + 1)
                bmqDic[key] = result.surveyResults[i]

            spamwriter.writerow(bmqDic)


def exportRAQPushCount():
    connect('az', host=db_engine.host)
    results = surveyInstanceDB.SurveyLog.objects()
    aes_cipher = aes.AESCipher(aes.aes_key)
    for result in results:
        if 'RAQ' == aes_cipher.decrypt(result.survey):
            print result.day


def createSurveyResultOffline():
    connect('az', host=db_engine.host)
    survey = db_engine.querySurveyByName("BMQ-G")
    with open('offlinesurvey/bmq-g.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar=',')
        for row in spamreader:
            d = time.mktime(datetime.datetime.strptime(row[1], "%d-%b-%y").timetuple())
            offline = db_engine.SurveyResultOffline(name=survey["name"], patientCode=row[0], createdDate=d,
                                                    des=survey["des"], surveyId=str(survey["id"]))
            results = []
            results.append(row[2])
            results.append(row[3])
            results.append(row[4])
            results.append(row[5])
            results.append(row[6])
            results.append(row[7])
            results.append(row[8])
            results.append(row[9])
            offline.surveyResults = results
            offline.save()

    survey = db_engine.querySurveyByName("LSQ-V1")
    with open('offlinesurvey/lsq-v1.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar=',')
        for row in spamreader:
            d = time.mktime(datetime.datetime.strptime(row[1], "%d-%b-%y").timetuple())
            offline = db_engine.SurveyResultOffline(name=survey["name"], patientCode=row[0], createdDate=d,
                                                    des=survey["des"], surveyId=str(survey["id"]))
            results = []
            results.append(row[2])
            results.append(row[3])
            results.append(row[4])

            offline.surveyResults = results
            offline.save()

    survey = db_engine.querySurveyByName("LSQ-V2")
    with open('offlinesurvey/lsq-v2.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar=',')
        for row in spamreader:
            d = time.mktime(datetime.datetime.strptime(row[1], "%d-%b-%y").timetuple())
            offline = db_engine.SurveyResultOffline(name=survey["name"], patientCode=row[0], createdDate=d,
                                                    des=survey["des"], surveyId=str(survey["id"]))
            results = []
            results.append(row[2])
            results.append(row[3])
            results.append(row[4])

            offline.surveyResults = results
            offline.save()

    survey = db_engine.querySurveyByName("RAQ")
    with open('offlinesurvey/raq.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar=' ')
        for row in spamreader:
            d = time.mktime(datetime.datetime.strptime(row[1], "%d-%b-%y").timetuple())
            offline = db_engine.SurveyResultOffline(name=survey["name"], patientCode=row[0], createdDate=d,
                                                    des=survey["des"], surveyId=str(survey["id"]))
            results = []
            results.append(row[2])
            results.append(row[3])
            results.append(row[4])
            results.append(row[5])
            results.append(row[6])
            results.append(row[7])
            results.append(row[8])
            results.append(row[9])
            results.append(row[10])
            results.append(row[11])
            results.append(row[12])
            results.append(row[13])

            offline.surveyResults = results
            offline.save()


if __name__ == "__main__":
    exportBMQ()
    exportLSQ('LSQ-V1')
    exportLSQ('LSQ-V2')
    exportRAQ()
    # exportRAQPushCount()
    # createSurveyResultOffline()
